package com.ruoyi.framework.config.mybatisplus.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.DataPermissionHandler;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysRoleMenu;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.Parenthesis;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;

import java.util.*;

@Slf4j
public class MyDataPermissionUtil {

    /**
     * 全部数据权限
     */
    public static final String DATA_SCOPE_ALL = "1";

    /**
     * 自定数据权限
     */
    public static final String DATA_SCOPE_CUSTOM = "2";

    /**
     * 部门数据权限
     */
    public static final String DATA_SCOPE_DEPT = "3";

    /**
     * 部门及以下数据权限
     */
    public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";

    /**
     * 仅本人数据权限
     */
    public static final String DATA_SCOPE_SELF = "5";

    /**
     * 组装SQL条件字符
     *
     * @param user
     * @return
     */
    public static String buildDataFilter(SysUser user,List<SysRoleMenu> roleMenus) {

        StringBuilder sqlString = new StringBuilder();

        List<String> conditions = new ArrayList<String>();

        /**
         * 获取当前用户角色
         */
        for (SysRole role : user.getRoles()) {

            String dataScope = role.getDataScope();
            if (conditions.contains(dataScope) || StringUtils.equals(role.getStatus(), UserConstants.ROLE_DISABLE))
            {
                continue;
            }

            if(roleMenus!=null){
                boolean isFind = false;
                for(SysRoleMenu roleMenu : roleMenus){
                    if(roleMenu.getRoleId() == role.getRoleId()){
                        isFind = true;
                        break;
                    }
                }
                if (!isFind)
                {
                    continue;
                }
            }

            if (DATA_SCOPE_ALL.equals(dataScope)) {
                //全部
                sqlString = new StringBuilder();
                conditions.add(dataScope);
                break;
            } else if (DATA_SCOPE_CUSTOM.equals(dataScope) ) {
                //自定数据权限
                sqlString.append(
                        StringUtils.format(
                                " OR create_by IN ( select user_name from sys_user stu,sys_role_dept srd where stu.dept_id=srd.dept_id and role_id= '{}' ) ",
                                role.getRoleId()));
            } else if (DATA_SCOPE_DEPT.equals(dataScope) ) {
                //当前部门数据权限
                sqlString.append(
                        StringUtils.format(
                                " OR create_by IN (select user_name from sys_user where dept_id= '{}' ) ",
                                user.getDeptId()));
            } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope) ) {
                //部门及以下数据权限
                sqlString.append(
                        StringUtils.format(
                                " OR create_by IN ( select user_name FROM sys_user stu,sys_dept sd WHERE stu.dept_id=sd.dept_id and (sd.dept_id = '{}' or find_in_set( '{}' , sd.ancestors )) )",
                                user.getDeptId(), user.getDeptId()));
            } else if (DATA_SCOPE_SELF.equals(dataScope) ) {
                //仅本人数据权限
                sqlString.append(StringUtils.format(" OR create_by = '{}' ", user.getUserName()));
            }
            conditions.add(dataScope);
        }
        if(StringUtils.isNotEmptyIncludeNull(sqlString.toString())){
            return "(" + sqlString.substring(4) + ")";
        }
        return sqlString.toString();
    }
}
